<?php

namespace common\filters;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * Cors filter implements [Cross Origin Resource Sharing](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
 *
 * @author Philippe Gaultier <pgaultier@gmail.com>
 * @since 2.0
 */
class Cors extends \yii\filters\Cors {

    /**
     * @var array Basic headers handled for the CORS requests.
     */
    public $cors = [
        'Origin' => ['*'],
        'Access-Control-Request-Method' => ['GET', 'POST', 'HEAD', 'OPTIONS'],
        'Access-Control-Request-Headers' => ['*'],
        'Access-Control-Allow-Credentials' => null,
        'Access-Control-Max-Age' => 86400,
        'Access-Control-Expose-Headers' => [],
    ];

    public function beforeAction($action) {
        if (in_array('*', $this->cors['Origin'], true)) {
            $allowOrigins = ArrayHelper::getValue(Yii::$app->params, 'crossDomains', []);
            if (!empty($allowOrigins)) {
                $this->cors['Origin'] = array_values($allowOrigins);
            }
        }
        return parent::beforeAction($action);
    }

}
